<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\BO\ConvertibleCard\Constant as ConvertibleCardConstant;
use App\Entity\DistributorPosterEntity;
use App\Entity\WechatUserEntity;
use App\Events\DistributionPosterEvent;
use App\Services\api\ILocationService;
use App\Services\Code\HttpResponse;
use App\Services\Distribution\Poster;
use App\Services\UserBalanceService;
use App\Services\UserCenterService;
use App\ServicesNew\ConvertibleCardService;
use App\VO\Usercenter\Builder as UsercenterVOBuilder;
use App\VO\Usercenter\DetailsRewards\Builder as DetailRewardsVOBuilder;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserCenterController extends BaseController
{
    /**
     * 用户中心
     * @return JsonResponse
     *
     * @param Request $request
     * @param ILocationService $locationService
     *
     * @api {get} /usercenter
     * @apiVersion 0.0.0
     * @apiName usercenter
     * @apiGroup usercenter
     * @apiDescription 用户中心
     *
     * @apiSuccessExample {json} success:
     * {"code":200,"message":"ok","data":{"user":{"id":260,"name":"\u4f55\u6b62\u4e03\u516b","password":"123456","phone":"18672457160","phone_verified_at":"2020-01-08 10:47:23","last_login_at":"2020-09-09 18:53:14","openid":"oVCNz0bPmgZ--mFyi2N3Xhm_Q5ao","enabled":1,"created_at":"2020-01-08 10:47:23","updated_at":"2020-09-09 18:53:14","user_channelid":0},"distributors":{"id":125,"dis_id":260,"dis_name":"\u4f55\u6b62\u4e03\u516b","phone":"18672457160","type":2,"balance":"2640.00","freeze_balance":"0.00","pre_balance":"0.00","description":null,"file1":null,"file2":null,"deleted_at":null,"status":0,"created_at":"2020-01-08 10:56:03","updated_at":"2020-08-06 18:08:57"},"advertImage":[{"advert_title":"","advert_url":"","image":"\/default_banner01.png"}],"tel":"tel:4006886758"}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function index(Request $request, ILocationService $locationService, ConvertibleCardService $convertibleCardService, UserCenterService $userCenterService)
    {
        $userEntity = $this->getUserEntity();
        $userInfo = null;
        if ($userEntity) {
            $userInfo = $userCenterService->getUserInfo($userEntity);
            //分销事件
            if (!DistributorPosterEntity::isExisted($userEntity->getUserId())) {
                event(new DistributionPosterEvent($userEntity));
            }
        }

        $cityId = $this->getUserLocationCityId();
        $areaEntity = $locationService->getCityById($cityId);
        $tel = ConvertibleCardConstant::CUSTOMERSERVICE_PHONENUMBER;

        #有可使用的显示：xx张可使用（用完的、过期的不算
        $availableConvertibleCardCount = $convertibleCardService->userAvailableCardCount($userEntity->getUserId());

        //获取广告图片
        // $advertImage = (new AdvertService())->getAd($areaEntity->getId(), AdvertInc::ADVERT_POSITION_USERCENTER);
        $vo = (new UsercenterVOBuilder())->buildDetail([
            'user' => $userInfo,
            // 'distributors' => $distributors,
            // 'advertImage' => $advertImage,
            'tel' => $tel,
            'available_convertiblecard_count' => $availableConvertibleCardCount,
        ]);
        return $this->showJsonResult(200, 'ok', $vo);
    }

    public function certification()
    {
        return view('user_center.certification');
    }

    public function transferWechat()
    {
        return view('user_center.transferWechat');
    }

    /**
     *
     * @api {get} /detailsRewards
     * @apiVersion 0.0.0
     * @apiName detailsRewards
     * @apiGroup usercenter
     * @apiDescription 用户赏金列表
     *
     * @apiSuccessExample {json} success:
     * {"code":200,"message":"ok","data":{"balance":"2640.00","preBalance":"0.00","records":[{"id":26,"dis_id":260,"type":4,"money":"120.00","created_at":"2020-08-06 18:08:57","updated_at":"2020-08-06 18:08:57"},{"id":25,"dis_id":260,"type":3,"money":"-120.00","created_at":"2020-08-06 18:08:15","updated_at":"2020-08-06 18:08:15"},{"id":24,"dis_id":260,"type":4,"money":"90.00","created_at":"2020-06-19 15:47:06","updated_at":"2020-06-19 15:47:06"},{"id":23,"dis_id":260,"type":3,"money":"-120.00","created_at":"2020-04-10 16:43:38","updated_at":"2020-04-10 16:43:38"},{"id":22,"dis_id":260,"type":3,"money":"-90.00","created_at":"2020-03-29 09:59:28","updated_at":"2020-03-29 09:59:28"},{"id":11,"dis_id":260,"type":4,"money":"72.00","created_at":"2020-03-15 11:03:30","updated_at":"2020-03-15 11:03:30"},{"id":10,"dis_id":260,"type":3,"money":"-72.00","created_at":"2020-03-15 10:51:23","updated_at":"2020-03-15 10:51:23"},{"id":9,"dis_id":260,"type":3,"money":"-150.00","created_at":"2020-03-06 09:32:44","updated_at":"2020-03-06 09:32:44"},{"id":7,"dis_id":260,"type":3,"money":"-90.00","created_at":"2020-03-05 16:46:07","updated_at":"2020-03-05 16:46:07"},{"id":6,"dis_id":260,"type":4,"money":"150.00","created_at":"2020-03-05 16:43:00","updated_at":"2020-03-05 16:43:00"},{"id":5,"dis_id":260,"type":3,"money":"-150.00","created_at":"2020-03-05 16:09:41","updated_at":"2020-03-05 16:09:41"}]}}
     * @apiErrorExample {json} fail:
     *     {"code":201,"message":"FAILED"}
     */
    public function detailsRewards()
    {
        $userBalanceService = new UserBalanceService($this->getUserEntity());
        $distributor = $userBalanceService->getDistributorEntity();
        $records = $userBalanceService->getTransactionRecordEntityList();
        $vo = (new DetailRewardsVOBuilder())->buildDetail([
            'records' => $records,
            'distributor' => $distributor,
        ]);
        return $this->showJsonResult(200, 'ok', $vo);
    }

    private function getDistributors($user)
    {
        if (!$user) {
            return;
        }
        $where['dis_id'] = $user->getUserId();
        return DB::table('distributors')
            ->where($where)
            ->first();
    }

    /**
     * 主动更新用户信息
     * @param string $openid
     * @param Request $request
     * @return JsonResponse
     *
     * @api {post} /user/wechat/{openid} 用户微信信息更新 头像、昵称、性别、城市等
     * @apiVersion 1.0.0
     * @apiName nickname
     * @apiGroup usercenter
     * @apiDescription 用户微信信息更新 头像、昵称、性别、城市等
     *
     * @apiParam {string} nickname 昵称
     * @apiParam {string} headimgurl 头像
     * @apiParam {string} [sex] 性别
     * @apiParam {string} [city] 城市
     * @apiParam {string} [province] 省份
     *
     * @apiSuccessExample {json} success:
     *     {"code":200,"message":"success","data":{"id":263,"openid":"28DbbotH665235828154318848","nickname":"ikaifa","sex":"0","language":"","city":"","province":"","country":"\u4e2d\u56fd","headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/8Lruau75DdwukEibibb93FWHZdYiabbI6wFLrYCNKXT9NFtE8gUHQ6VibImibibNaI7T486J3L4yXweydfwSuju56gWMfPp6MH9xpT\/132","privilege":"","unionid":"","user_id":272,"enabled":1,"created_at":"2020-02-24 14:21:56","updated_at":"2020-09-22 15:05:11","channelid":11}}
     * @apiErrorExample {json} fail:
     *     {"code":1100,"message":"openid or nickname or headimgurl empty"}
     */
    public function updateWechat(string $openid, Request $request)
    {
        $nickname = $request->input('nickname');
        $headimgurl = $request->input('headimgurl');
        $sex = $request->input('sex');
        $city = $request->input('city');
        $province = $request->input('province');

        //验证必要参数
        if (!$openid || !$nickname || !$headimgurl) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_PARAMS_ERR, 'openid or nickname or headimgurl empty'));
        }

        $wechatUserEntity = WechatUserEntity::findByOpenid($openid);
        if ($wechatUserEntity === null) {
            return response()->json(HttpResponse::respFail(HttpResponse::CODE_DATA_EMPTY, '用户不存在'));
        }

        $wechatUserEntity->setUpdatedAt(Carbon::now()->toDateTimeString());
        $wechatUserEntity->setNickname($nickname);
        $wechatUserEntity->setHeadimgurl($headimgurl);

        $sex && $wechatUserEntity->setSex($sex);
        $city && $wechatUserEntity->setCity($city);
        $province && $wechatUserEntity->setProvince($province);

        $wechatUserEntity->save();
        Log::info('用户微信信息更新', $request->all());

        return response()->json(HttpResponse::respSuccess(HttpResponse::CODE_SUCCESS, $wechatUserEntity->toArray()));
    }

    /**
     * 获取分销海报
     * @param string $openid
     * @param int $user_id;
     *
     * @return JsonResponse
     *
     * @api {get} /user/poster 获取分销海报
     * @apiVersion 1.0.0
     * @apiName poster
     * @apiGroup usercenter
     * @apiDescription 获取分销海报
     *
     * @apiParam {string} openid openid
     * @apiParam {number} user_id 用户ID
     *
     * @apiSuccessExample {json} success:
     *     {"code":200,"message":"success","data":{"id":1,"created_at":"2020-10-12 20:34:48","updated_at":"2020-10-12 20:34:51","user_id":332,"openid":"adjlaaskjdas","url":"http:\/\/"}}
     * @apiErrorExample {json} fail:
     *     {"code":1100,"message":"openid or nickname or headimgurl empty"}
     */
    public function poster(Request $request)
    {
        $userId = (int)$request->input('user_id');
        $res = DistributorPosterEntity::findByUserId($userId);
        if (empty($res)) {
            return response()->json(HttpResponse::respSuccess(HttpResponse::CODE_SUCCESS, []));
        }
        return response()->json(HttpResponse::respSuccess(HttpResponse::CODE_SUCCESS, $res->toArray()));
    }
}
